package com.tianpengtech.front.web.task;

import com.alibaba.druid.util.StringUtils;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.upload.UploadFile;
import com.tianpengtech.admin.appsetting.AppSettingDao;
import com.tianpengtech.admin.dictionary.DictionaryDao;
import com.tianpengtech.admin.task.SendTaskSMSThread;
import com.tianpengtech.admin.task.SysConfigDao;
import com.tianpengtech.common.GlobalConfigConstant;
import com.tianpengtech.common.exception.ValidateException;
import com.tianpengtech.common.im.kit.PushKit;
import com.tianpengtech.common.model.appsetting.AppSetting;
import com.tianpengtech.common.model.authenticate.Authenticate;
import com.tianpengtech.common.model.fair.Fair;
import com.tianpengtech.common.model.fairorder.FairOrder;
import com.tianpengtech.common.model.task.Task;
import com.tianpengtech.common.model.task.TaskSource;
import com.tianpengtech.common.model.task.TaskWh;
import com.tianpengtech.common.model.user.User;
import com.tianpengtech.common.util.IpKit;
import com.tianpengtech.common.util.JsonUtil;
import com.tianpengtech.common.util.QiNiuUtil;
import com.tianpengtech.common.util.XxxUtil;
import com.tianpengtech.front.web.common.controller.BaseController;
import com.tianpengtech.front.web.common.interceptor.PassportInterceptor;
import com.tianpengtech.front.web.fair.FairService;
import com.tianpengtech.front.web.login.LoginService;

import javax.persistence.criteria.CriteriaBuilder;

import java.io.FileInputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Controller for task management.
 * 
 * @author Delicate
 */
// @Clear(PassportInterceptor.class)
public class TaskWebController extends BaseController {
	private TaskService service = new TaskService();
	private FairService fairService = new FairService();
	private DictionaryDao dictionaryDao = new DictionaryDao();
	private int COOKIE_TIME_OUT=1000*60*60*24*30;
	public void index() {
		render("task_list.html");
	}

	public void list() {
		int pageNum = getParaToInt(GlobalConfigConstant.PARAM_NAME_PAGENUM, GlobalConfigConstant.DEFAULT_VALUE_PAGENUM);
		int pageSize = getParaToInt(GlobalConfigConstant.PARAM_NAME_PAGESIZE,
				GlobalConfigConstant.DEFAULT_VALUE_PAGESIZE);
		Map<String, Object> params = new HashMap<>();
		params.put("taskName", getPara("taskName"));
		params.put("taskStatus", getPara("status"));
		User user = getAttr(LoginService.loginAccountCacheName);
		params.put("user", user.get(User.ID));
		Page<Task> page = service.task(pageNum, pageSize, params);
		renderJson(page);
	}

	public void form() {
		render("task_add_new.html");
	}

	public void formNew() {
		User user = getAttr(LoginService.loginAccountCacheName);
		if (user == null) {
			renderJson(Ret.fail("msg", "未登录"));
			return;
		}
		Authenticate auth = service.isCreate(user.get(User.ID));

		if (auth == null) {
//			redirect("/passport/detail?id=" + user.get(User.ID));
			setAttr("status",-1);
			render("task_fail.html");
			return;
		} else if (auth.getInt(Authenticate.STATUS) == Authenticate.STATUS_SUCCESS) {
			setAttr("domain", QiNiuUtil.DOMAIN);
			//setAttr("priceList", service.getPriceList());改成通过预算来发布任务
			setAttr("totalPriceList", service.getTaskTotalPriceList());
			render("task_add_new.html");
			return;
		} else if (auth.getInt(Authenticate.STATUS) == Authenticate.STATUS_APPROVING) {
			redirect("/passport/detail?id=" + user.get(User.ID));
			return;
		} else if (auth.getInt(Authenticate.STATUS) == Authenticate.STATUS_FAILURE) {
			redirect("/passport/detail?id=" + user.get(User.ID));
			return;
		}
	}

	/**
	 * 任务创建
	 */
	@Before({ Tx.class })
	public void save() {
		try {
			Task task = getModel(Task.class, "task");
			String[] source = getParaValues("source");
			User user = getAttr(LoginService.loginAccountCacheName);
			if (user == null) {
				renderJson(Ret.fail("msg", "未登录"));
				return;
			}
			task.set(Task.CREATE_USER, user.get(User.ID));
			service.save(task, source);
			renderJson(JsonUtil.printObject(task.get(Task.ID)));
		} catch (ValidateException e) {
			renderJson(JsonUtil.printError(e.getMessage()));
		}
	}

	public void dispatcher() {
		int id = getParaToInt("id");
		Task task = Task.dao.findById(id);
		User user = getAttr(LoginService.loginAccountCacheName);
		if (task.getInt(Task.EXTENSION_TYPE) == Task.EXT_TYPE_ZD) {
			// 如果是指定主播， 跳转到选择主播页面
			setAttr("task", task.get(Task.ID));
			setAttr("taskObj",task);
			forwardAction("/platform/task/choiceFairNew");
		} else {
			// 如果是认领，跳转到创建成功页面
			setAttr("task", task);
			setAttr("isShowQrCode",service.isShowQrCode(task, user.getLong(User.ID)));
			PushKit.pushSystemMessageNow(
					"用户【" + XxxUtil.hiddenMobile(user.getStr(User.MOBILE)) + "】发布了任务《" + task.getStr(Task.TASK_TITLE) + "》");
			render("task_success.html");
		}
	}

	/**
	 * 选择网红页面
	 */
	public void changeFair() {

		render("task_wh.html");
	}

	public void choiceFairNew() {
		setAttr("task", getAttr("task"));
		setAttr("taskObj", getAttr("taskObj"));
		setAttr("region", Db.findByCache(Fair.FAIR_CACHE_NAME, Fair.FAIR_CACHE_REGION,
				"select REGION_ID,REGION_NAME from region where PARENT_ID=1"));
		setAttr("platform", dictionaryDao.readParents(10055));
		setAttr("channel",dictionaryDao.readParents(10056));
		setAttr("prices",service.getTaskTotalPriceList());
		setAttr("feature", AppSettingDao.dao.getAppSettingByCategory(AppSetting.FANS));
		render("task_fair_new.html");
		
	}

	public void success() {
		render("task_success.html");
	}

	/**
	 * 选择完网红后保存
	 */
	@Before(Tx.class)
	public void saveTaskWait() {
		// String[] fairs=getParaValues("fairs");
		User user = getAttr(LoginService.loginAccountCacheName);
		String fairsStr = getPara("fairs");
		String[] fairs = fairsStr.split(",");
		if (fairs == null || fairs.length == 0) {
			renderJson(Ret.fail("msg", "保存失败，数据不正确"));
			return;
		}
		String task = getPara("task");
		if (StrKit.isBlank(task)) {
			renderJson(Ret.fail("msg", "保存失败，数据不正确"));
			return;
		}
		Ret ret = service.saveTaskWait(fairs, task);
		if (ret.isOk()) {
			Task temp = service.findTaskById(task);
			temp.set(Task.WH_NUMBER, fairs.length).update();
			setAttr("task",temp);
			setAttr("isShowQrCode",service.isShowQrCode(temp, user.getLong(User.ID)));
			setAttr("fairs", fairService.findByWhite(task));
			PushKit.pushSystemMessageNow(
					"用户【" + XxxUtil.hiddenMobile(user.getStr(User.MOBILE)) + "】发布了任务《" + temp.getStr(Task.TASK_TITLE) + "》");
			render("task_success.html");
		} else {
			renderJson(ret);
		}
	}

	/**
	 * 任务点击数统计
	 */
	@Clear(PassportInterceptor.class)
	@Before(TaskCountValidator.class)
	public void taskCount() {
		String ua = getHeader("User-Agent");
		String ref = getHeader("Referer");
		String ip = IpKit.getRealIp(getRequest());
		String code = getPara("code");
		Map<String,Object> wxUser = getSessionAttr("wxuser");
		
		String avatar="";
		String nickName="";
		System.out.println("taskCount:-------->"+wxUser);
		if(wxUser!=null){
			avatar = (String) wxUser.get("avatarUrl");
			nickName = (String) wxUser.get("nickName");
		}
		
		//为客户端生成TOKEN值，这样方便统计信息
		String token = getCookie("token");
		if(StringUtils.isEmpty(token)){
			token = UUID.randomUUID().toString();
			setCookie("token",token,COOKIE_TIME_OUT);
		}
		service.saveTaskClick(ref, ua, ip, code,token,avatar,nickName);
		renderJson(JsonUtil.printSuccess("记录成功"));
	}

	/**
	 * 任务转化数统计
	 */
	@Clear(PassportInterceptor.class)
	@Before(TaskCountValidator.class)
	public void taskCvs() {
		String ua = getHeader("User-Agent");
		String ref = getHeader("Referer");
		String ip = IpKit.getRealIp(getRequest());
		String code = getPara("code");
		String token = getCookie("cvs_token");
		Map<String,Object> wxUser = getSessionAttr("wxuser");
		String avatar="";
		String nickName="";
		if(wxUser!=null){
			avatar = (String) wxUser.get("avatarUrl");
			nickName = (String) wxUser.get("nickName");
		}
		
		if(StringUtils.isEmpty(token)){
			token = UUID.randomUUID().toString();
			setCookie("cvs_token",token,COOKIE_TIME_OUT);
		}
		service.saveTaskCvs(ref, ua, ip, code,token,avatar,nickName);
		renderJson(JsonUtil.printSuccess("记录成功"));
	}

	public void click() {
		render("click.html");
	}

	/**
	 * 任务详情页
	 */
	public void detail() {
		String id = getPara("id");
		if (StrKit.isBlank(id)) {
			renderJson(Ret.fail());
			return;
		}
		Task task = service.findTaskById(id);
		if (task == null) {
			renderJson(Ret.fail("msg", "任务不存在"));
			return;
		}
		List<Fair> fairs = fairService.findByTask(id);
		if (task.getInt(Task.STATUS).intValue() == Task.STATUS_WAIT) {
			setAttr("task", task.get(Task.ID));
			forwardAction("/platform/task/choiceFairNew");
			return;
		}
		setAttr("task", task);
		setAttr("fairs", fairs);
		renderTemplate("task_detail.html");
	}
	
	
	/**
	 * 保存离线任务相关数据信息
	 */
	
	public void saveOffLineTask(){
		Task task = getModel(Task.class);
		try {
			User user = getAttr(LoginService.loginAccountCacheName);
			task.set(Task.CREATE_USER, user.get(User.ID));
			service.saveOfflineTask(task);
			renderJson(Ret.ok("msg", "保存成功，请保持电话畅通，我们会有工作人员与你取得联系"));
		} catch (ValidateException e) {
			renderJson(Ret.fail("msg", e.getMessage()));
		}
	}

	/**
	 * 获取任务资源
	 */
	public void taskSource() {
		String id = getPara("id");
		if (StrKit.isBlank(id)) {
			renderJson(Ret.fail("msg", "任务不存在"));
			return;
		}
		List<TaskSource> source = service.findSourceByTask(Integer.parseInt(id));
		setAttr("sources", source);
		setAttr("id", id);
		render("task_perview.html");
	}

	/**
	 * 保存排序
	 */
	@Before({Tx.class })
	public void saveTaskSource() {
		String id = getPara("id");
		if (StrKit.isBlank(id)) {
			renderJson(Ret.fail("msg", "任务不存在"));
			return;
		}
		Enumeration<String> names = getParaNames();
		Map<String, String> sources = new HashMap<>();
		while (names.hasMoreElements()) {
			String key = names.nextElement();
			sources.put(key, getPara(key));
		}
		service.saveTaskSource(sources);
		redirect("/platform/task/taskSource?id=" + id);
	}

	
	public void secondTaskStep(){
		renderTemplate("second-task-step.html");
	}
	
	@Clear(PassportInterceptor.class)
	public void viewH5(){
		int id = getParaToInt(Task.ID,GlobalConfigConstant.DEFAULT_VALUE_ZERO);
		setAttr("id", id);
		renderTemplate("h5_preview.html");
	}
	
	@Clear(PassportInterceptor.class)
	public void showH5(){
		
		int id = getParaToInt(Task.ID,GlobalConfigConstant.DEFAULT_VALUE_ZERO);
		List<TaskSource> source = service.findSourceByTask(id);
		setAttr("sources", source);
		setAttr("task", Task.dao.findById(id));
		renderTemplate("showH5.html");
	}
	
	
	public void editTask(){
		int id = getParaToInt(Task.ID,GlobalConfigConstant.DEFAULT_VALUE_ZERO);
		//检查当前任务是否支付，假如支付只能修改图片
		String sql = "select * from fair_order where obj_id=? and opt_type=?";
		FairOrder order = FairOrder.dao.findFirst(sql,id, FairOrder.OPT_TYPE_TASK);
		boolean payed = (order==null)?false:(order.getInt(FairOrder.STATUS)==FairOrder.STATUS_PAYED);
		Task task = Task.dao.findById(id);
		setAttr("task", task);
		List<TaskSource> source = service.findSourceByTask(id);
		setAttr("sources", source);
		if(payed){//假如支付了，只能修改图片信息
			
			renderTemplate("edit-task-source.html");
		}else{
			renderTemplate("edit-task-source.html");
		}
	}
	
	public void doUpdateTask(){
		int id = getParaToInt(Task.ID,GlobalConfigConstant.DEFAULT_VALUE_ZERO);
		String desc = getPara("desc","");
		Task task = Task.dao.findById(id);
		User user = getAttr(LoginService.loginAccountCacheName);
		
		//判断当前任务是否有人接单，如果有，则禁止修改
		String sql="select * from "+TaskWh.dao.tableName()+" where task_id=?";
		List<TaskWh> tasks = TaskWh.dao.find(sql,id);
		
		if(tasks.size()>0 && task.getInt(Task.EXTENSION_TYPE)==Task.EXT_TYPE_RL){
			renderJson(JsonUtil.printError("当前任务已经有人接单，禁止修改"));
			return;
		}
		
		if(task.getLong(Task.CREATE_USER)==user.getLong(User.ID)){
			task.set(Task.TASK_DESCRIPTION, desc);
			task.set(Task.STATUS, Task.STATUS_APPROVING);
			task.update();
			renderJson(JsonUtil.printSuccess("更新成功"));
		}else{
			renderJson(JsonUtil.printError("当前任务非本人所创建，禁止修改"));
		}
		
	}
	
	public void doUpdateTaskSource(){
		int taskId = getParaToInt("taskId",0);
		String desc = getPara("desc","");
		User user = getAttr(LoginService.loginAccountCacheName);
		Task task = Task.dao.findById(taskId);
		//判断当前任务是否有人接单，如果有，则禁止修改
		String sql="select * from "+TaskWh.dao.tableName()+" where task_id=?";
		List<TaskWh> tasks = TaskWh.dao.find(sql,taskId);
		if(tasks.size()>0 && task.getInt(Task.EXTENSION_TYPE)==Task.EXT_TYPE_RL){
			renderJson(JsonUtil.printError("当前任务已经有人接单，禁止修改"));
			return;
		}
		
		if(task.getLong(Task.CREATE_USER)==user.getLong(User.ID)){
			task.set(Task.TASK_DESCRIPTION, desc);
			task.set(Task.STATUS, Task.STATUS_APPROVING);
			task.update();
			
//			String[] source = getParaValues("source");
//			sql = "delete from "+TaskSource.dao.tableName()+" where task_id=?";
//			Db.update(sql,taskId);
//			if (source!=null && source.length>0){
//	            for (int i=0;i<source.length;i++) {
//	                String s=source[i];
//	                TaskSource ts = new TaskSource();
//	                ts.set(TaskSource.TASK_ID,taskId);
//	                ts.set(TaskSource.SOURCE,s);
//	                ts.set(TaskSource.SORT,i+1);
//	                ts.set(TaskSource.CREATE_DATE,new Date());
//	                ts.save();
//	            }
//	        }
			renderJson(JsonUtil.printSuccess("更新成功"));
		}else{
			renderJson(JsonUtil.printError("当前任务非本人所创建，禁止修改"));
		}
	}
	
	public void deleteTaskSource(){
		int sourceId = getParaToInt("sourceId",0);
		boolean result = TaskSource.dao.deleteById(sourceId);
		if(result){
			renderJson(JsonUtil.printSuccess("删除成功"));
		}else{
			renderJson(JsonUtil.printSuccess("删除失败"));
		}
		
	}
	
	
	
	
	
	public void ts(){
		String task = "3117";
		Task temp = service.findTaskById(task);
		setAttr("task",temp);
		setAttr("isShowQrCode",service.isShowQrCode(temp, 12));
		setAttr("fairs", fairService.findByWhite(task));
		render("task_success.html");
	}
	
	public void infoSomeone(){
		new TaskService().infoSomeOneWithoutApply();
		renderJson(JsonUtil.printSuccess("短信通知成功"));
	}
	
	
	public void infoFairSMS(){
		if(SysConfigDao.ME.isSendTaskSMS()){
			String sql="select * from "+Fair.dao.tableName()+" where status=? and deletetag=?";//找出所有认证通过的网红，发送数据信息
			List<Fair> fair =  Fair.dao.find(sql,Fair.STATUS_SUCCESS,Fair.DELETE_STATUS_NO);
			SendTaskSMSThread thread = new SendTaskSMSThread(fair);
			thread.start();
		}
		renderJson(JsonUtil.printSuccess("短信通知成功"));
	}
	
	public void taskWh(){
		String task = "3117";
		Task temp = service.findTaskById(task);
		setAttr("taskObj",temp);
		setAttr("task", task);
		render("task_fair_new.html");
	}
}
